package cn.mothin.service.setup;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.dao.SystemUserDao;
import cn.mothin.dictionary.SystemUserState;
import cn.mothin.entity.SystemUser;
import cn.mothin.frame.core.base.BaseService;
import cn.mothin.frame.help.Password;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.ObjectUtil;
import cn.mothin.vo.setup.RegisterSuperForm;

@Service("54052c7a7b0bf81ac00a981e")
public class RegisterSuperService extends BaseService {
	// 超级用户dao
	@Autowired
	private SystemUserDao systemUserDao = null;

	/**
	 * 查询超级用户是否存在
	 * 
	 * @return
	 */
	public boolean querySuperUserExist() {
		return systemUserDao.querySuperUserExist();
	}
	
	/**
	 * 账号是否存在
	 * 
	 * @param form
	 * @return
	 */
	public boolean findSystemUsersByAccount(RegisterSuperForm form) {
		List<SystemUser> list = systemUserDao.findSystemUsersByAccount(form.getSystemUser().getAccount());
		if(list != null && list.size() > 0) {
			return true;
		} 
		return false;
	}

	/**
	 * 添加超级用户
	 * 
	 * @param registerSuperForm
	 * @param loginUser
	 * @return true：成功，false：已存在记录
	 */
	public int addSuperUser(RegisterSuperForm form) {
		if (querySuperUserExist()) {
			return 1;
		}
		if(findSystemUsersByAccount(form)) {
			return 2;
		}
		SystemUser systemUser = new SystemUser();
		ObjectUtil.SyncObjectsWithFields(systemUser, form.getSystemUser(),
				SystemUser.NAME, SystemUser.ACCOUNT, SystemUser.MOBILE,
				SystemUser.EMAIL);
		systemUser.setId(UniqueCode.make());
		systemUser.setState(SystemUserState.NORMAL.getId());
		systemUser.setPassword(Password.encrypt(form.getSystemUser()
				.getPassword()));
		systemUser.setSuperUser(true);
		systemUserDao.save(systemUser);
		return 0;
	}
}
